package cn.pku.sirx.snad.ads.context;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.pku.sirx.snad.ad.model.PageInfo;
import cn.pku.sirx.snad.ad.model.UserContext;
import cn.pku.sirx.snad.ad.model.WeightedKeyword;
import cn.pku.sirx.snad.ads.strategy.IKeywordReorderStrategy;
import cn.pku.sirx.snad.ads.strategy.IKeywordRetrievalStrategy;
import cn.pku.sirx.snad.ads.strategy.impl.KeywordReorderStrategyImpl;
import cn.pku.sirx.snad.ads.strategy.impl.KeywordRetrievalStrategyImpl;

/**
 * @author WangXiao
 */
public class UserContextFactory extends AbstractUserContextFactory {

	/**
	 * Get a single instance of UserContextFactory.
	 * 
	 * @return a single instance of UserContextFactory
	 */
	public static UserContextFactory getInstance() {
		return instance;
	}

	@Override
	public UserContext getUserContext(Map<String, String> userContextMap) {
		UserContext result = new UserContext();
		result.setUserId(userContextMap.get(USER_ID));
		result.setUserIp(userContextMap.get(USER_IP));
		PageInfo pageInfo = new PageInfo();
		pageInfo.setDomain(userContextMap.get(PAGE_DOMAIN));
		pageInfo.setReferer(userContextMap.get(PAGE_REFERER));
		pageInfo.setSummary(userContextMap.get(PAGE_SUMMARY));
		pageInfo.setTitle(userContextMap.get(PAGE_TITLE));
		pageInfo.setUrl(userContextMap.get(PAGE_URL));
		result.setPageInfo(pageInfo);
		result.setWeightedKeywords(getSerializableWeightedKeywords(result));
		return result;
	}

	private List<WeightedKeyword> getSerializableWeightedKeywords(
			UserContext userContext) {
		List<WeightedKeyword> keywords = keywordRetrievalStrategy
				.retrieveKeywords(userContext);
		keywords = keywordReorderStrategy.reorderKeywords(keywords);
		return new ArrayList<WeightedKeyword>(keywords);
	}

	private static IKeywordRetrievalStrategy keywordRetrievalStrategy = new KeywordRetrievalStrategyImpl();
	private static IKeywordReorderStrategy keywordReorderStrategy = new KeywordReorderStrategyImpl();
	private static UserContextFactory instance = new UserContextFactory();

}
